package com.xmut.mall.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.xmut.mall.auth.constant.AuthConstant;
import com.xmut.mall.auth.feign.ManagerFeignService;
import com.xmut.mall.auth.feign.MemberFeignService;
import com.xmut.mall.auth.feign.StoreFeignService;
import com.xmut.mall.auth.service.LoginService;
import com.xmut.mall.auth.utils.JWTUtils;
import com.xmut.mall.auth.utils.RespBean;
import com.xmut.mall.auth.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ManagerFeignService managerFeignService;

    @Autowired
    private StoreFeignService storeFeignService;

    /**
     * 普通登录
     * @param vo
     * @return
     */
    @Override
    public RespBean login(LoginVo vo) {
        RespBean respBean = memberFeignService.login(vo);
        if(respBean.getCode() == 201){
            // 登录成功 解析用户数据 权限服务生成token
            MemberVo member = JSON.parseObject(JSON.toJSONString(respBean.getObj()), MemberVo.class);
            // 生成token时加上浏览器的User-Agent防止token被人盗刷
            member.setUserAgent(request.getHeader("User-Agent"));
            member.setPassword(null); // 密码无需返回
            // 生成Token
            String accessToken = JWTUtils.createAccessToken(JSON.toJSONString(member));
            String refreshToken = JWTUtils.createRefreshToken(JSON.toJSONString(JSON.toJSONString(member)));
            LoginSuccessVo loginSuccessVo = new LoginSuccessVo();
            loginSuccessVo.setMember(member);
            loginSuccessVo.setAccessToken(accessToken);
            loginSuccessVo.setRefreshToken(refreshToken);
            return RespBean.success("登陆成功",loginSuccessVo);
        }else {
            // 登录失败
            return RespBean.error(respBean.getMessage());
        }
    }

    /**
     * 短信登录
     * @param vo
     * @return
     */
    @Override
    public RespBean smsLogin(SmsLoginVo vo) {
        String redisCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + vo.getMobile());
        if(!redisCode.equals(vo.getCode())){
            // 如果验证码对不上返回验证码错误
            return RespBean.error("验证码错误");
        }

        // 验证码对得上根据手机号码查出用户信息返回给前端
        RespBean userByPhone = memberFeignService.getUserByPhone(vo.getMobile());
        if(userByPhone.getCode() == 201){
            // 请求成功结构数据 给前端返回数据
            MemberVo memberVo = JSON.parseObject(JSON.toJSONString(userByPhone.getObj()), MemberVo.class);
            memberVo.setUserAgent(request.getHeader("User-Agent"));
            memberVo.setPassword(null); // 不需要密码
            // 生成Token

            String accessToken = JWTUtils.createAccessToken(JSON.toJSONString(memberVo));
            String refreshToken = JWTUtils.createRefreshToken(JSON.toJSONString(memberVo));
            LoginSuccessVo loginSuccessVo = new LoginSuccessVo();
            loginSuccessVo.setMember(memberVo);
            loginSuccessVo.setAccessToken(accessToken);
            loginSuccessVo.setRefreshToken(refreshToken);
            return RespBean.success("登录成功",loginSuccessVo);
        }else {
            // 没有找到该用户
            return RespBean.error(userByPhone.getMessage());
        }
    }

    /**
     * 管理端登录
     * @param vo
     * @return
     */
    @Override
    public RespBean managerLogin(LoginVo vo) {
        // 暂未设置数据库 暂时以静态代码登录
        RespBean respBean = managerFeignService.managerLogin(vo);
        if(respBean.getCode() == 201){
            // 查询到用户
            ManagerMemberVo managerMemberVo = JSON.parseObject(JSON.toJSONString(respBean.getObj()), ManagerMemberVo.class);
            managerMemberVo.setPassword(null);
            managerMemberVo.setUserAgent(request.getHeader("User-Agent"));

            // 生成token
            String accessToken = JWTUtils.createAccessToken(JSON.toJSONString(managerMemberVo));
            String refreshToken = JWTUtils.createRefreshToken(JSON.toJSONString(managerMemberVo));
            ManagerLoginSuccessVo successVo = new ManagerLoginSuccessVo();
            successVo.setManagerMember(managerMemberVo);
            successVo.setAccessToken(accessToken);
            successVo.setRefreshToken(refreshToken);
            return RespBean.success("登录成功",successVo);
        }else {
            // 查询失败或异常
            return respBean;
        }
    }

    /**
     * 商铺端 卖家登录
     * @param vo
     * @return
     */
    @Override
    public RespBean sellerLogin(LoginVo vo) {
        RespBean userInfoResp = memberFeignService.login(vo);
        System.out.println("测试userinfo:"+userInfoResp);
        if(userInfoResp.getCode() == 201){
            // 请求成功后
            MemberVo member = JSON.parseObject(JSON.toJSONString(userInfoResp.getObj()), MemberVo.class);
            member.setUserAgent(request.getHeader("User-Agent"));
            member.setPassword(null); // 不需要密码
            // 查询当前用户所属的商铺的情况
            RespBean storeResp = storeFeignService.getShopStatusByMemberId(member.getId());
            System.out.println("测试storeResp:"+storeResp);
            if(storeResp.getCode()==201){
                // 店铺存在并且审核通过
                // 进行Token生成
                String accessToken = JWTUtils.createAccessToken(JSON.toJSONString(member));
                String refreshToken = JWTUtils.createRefreshToken(JSON.toJSONString(member));
                LoginSuccessVo loginSuccessVo = new LoginSuccessVo();
                loginSuccessVo.setMember(member);
                loginSuccessVo.setAccessToken(accessToken);
                loginSuccessVo.setRefreshToken(refreshToken);

                return RespBean.success("登录成功",loginSuccessVo);
            }else {
                // 各种错误
                return storeResp;
            }
        }else {
            // 用户错误或不存在
            return userInfoResp;
        }
    }
}
